/**
 * Copyright 2010-present Facebook.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.op.mr3;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;

import com.facebook.Session;
import com.facebook.SessionDefaultAudience;
import com.facebook.SessionState;
import com.facebook.widget.FacebookDialog;
import com.facebook.widget.UserSettingsFragment;

public class FacebookLoginActivity extends FragmentActivity {

    private Session.StatusCallback mCallback;

    private UserSettingsFragment   mFragment;

    private boolean                canPresentShareDialog;

    private static ShareDialog     mDialog;

    private boolean                finished;

    public static void init(Activity activity) {
        mDialog = new ShareDialog(activity);
    }

    private class SessionStatusCallback implements Session.StatusCallback {

        @Override
        public void call(Session session, SessionState state, Exception exception) {
            ShareDialog dialog = mDialog;
            if (dialog == null) {
                return;
            }
            if (state == SessionState.OPENED) {
                dialog.show();
                FacebookLoginActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        FacebookLoginActivity.this.endLogIn();
                    }
                });
            } else {
                dialog.dismiss();
            }
        }
    }

    public static void startSharing(Activity activity, JSONObject data) {
        Session session = Session.getActiveSession();
        if (session != null && session.isOpened()) {
            ShareDialog dialog = mDialog;
            if (dialog != null) {
                dialog.show();
            }
            return;
        }

        Intent intent = new Intent(activity, FacebookLoginActivity.class);
        activity.startActivity(intent);
    }

    protected void endLogIn() {
        if (!finished) {
            finished = true;
            this.finish();
        }
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        finished = false;

        mCallback = new SessionStatusCallback();
        canPresentShareDialog = FacebookDialog.canPresentShareDialog(this, FacebookDialog.ShareDialogFeature.SHARE_DIALOG);
        //System.out.println("FragmentLoginActivity.onCreate():" + canPresentShareDialog);

        setContentView(R.layout.login_fragment_activity);
        FragmentManager fragmentManager = getSupportFragmentManager();
        mFragment = (UserSettingsFragment) fragmentManager.findFragmentById(R.id.login_fragment);
        mFragment.setSessionStatusCallback(mCallback);

        Session session = Session.getActiveSession();
        //System.out.println("FragmentLoginActivity.onCreate():" + session);
        //System.out.println("FragmentLoginActivity.onCreate():" + savedInstanceState);

        if (session == null) {
            if (savedInstanceState != null) {
                //System.out.println("FacebookLoginActivity.restoreSession");
                session = Session.restoreSession(this, null, mCallback, savedInstanceState);
            }
            if (session == null) {
                //System.out.println("FacebookLoginActivity.session still null");
                session = new Session(this);
            }
            Session.setActiveSession(session);

            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                //System.out.println("start read");
                Session.OpenRequest openRequest;
                openRequest = new Session.OpenRequest(mFragment);
                openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);

                session.openForRead(openRequest);
                return;
            }
        }

        onClickLogin();
    }

    private void onClickLogin() {
        Session session = Session.getActiveSession();
        System.out.println("FragmentLoginActivity.onClickLogin():" + session);
        if (!session.isOpened() && !session.isClosed()) {
            System.out.println("FragmentLoginActivity.onClickLogin.openForRead");
            session.openForRead(new Session.OpenRequest(this));
        } else {
            System.out.println("FragmentLoginActivity.onClickLogin.openActiveSession");
            Session.openActiveSession(this, mFragment, true, mCallback);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
    }
}
